﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace UserInterfaceLayer.User
{
    public partial class ChangePassword : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            lblFailure.Visible = false;
            lblWrongPassword.Visible = false;
            lblNewPasswordsDifferent.Visible = false;
            lblInvalidNewPassword.Visible = false;
            lblSuccessful.Visible = false;
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            DataAccessLayer.linqDatabaseDataContext db = new DataAccessLayer.linqDatabaseDataContext();
            int UserID = (int)Session["UserID"];
            DataAccessLayer.User User = DataAccessLayer.User.FindByUserID(db, UserID);

            if (User.Password == txtCurrentPassword.Text)
            {
                if (txtNewPassword.Text == txtConfirmNewPassword.Text)
                {
                    if (txtNewPassword.Text.Length > 0 && txtNewPassword.Text.Length <= 20)
                    {
                        try
                        {
                            DataAccessLayer.User newUser = new DataAccessLayer.User();
                            newUser.EditorUserID = UserID;
                            newUser.Enable = User.Enable;
                            newUser.FirstName = User.FirstName;
                            newUser.Image = User.Image;
                            newUser.IsDeleted = User.IsDeleted;
                            newUser.LastName = User.LastName;
                            newUser.Password = txtNewPassword.Text;
                            newUser.Timestamp = DateTime.Now;
                            newUser.UserID = User.UserID;
                            newUser.Username = User.Username;
                            db.Users.InsertOnSubmit(newUser);
                            db.SubmitChanges();
                            lblSuccessful.Visible = true;
                        }
                        catch (Exception)
                        {
                            lblFailure.Visible = true;
                            return;
                        }
                    }
                    else
                    {
                        lblInvalidNewPassword.Visible = true;
                    }
                }
                else
                {
                    lblNewPasswordsDifferent.Visible = true;
                }
            }
            else
            {
                lblWrongPassword.Visible = true;
            }
        }
    }
}